package com.mdd.maduoduo.wxapi;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.mdd.maduoduo.MyApplication;
import com.mdd.maduoduo.constants.CommonConstants;
import com.mdd.maduoduo.entity.AuthResp;
import com.mdd.maduoduo.event.WxLoginEvent;
import com.mdd.maduoduo.utils.RxBus;
import com.mdd.maduoduo.utils.ToastUtils;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {
    private IWXAPI api;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        api = WXAPIFactory.createWXAPI(this, CommonConstants.WX_APPID, false);
        api.handleIntent(getIntent(), this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        api.handleIntent(intent, this);
    }

    @Override
    public void onReq(BaseReq req) {
        // 微信发送的请求处理
    }

    @Override
    public void onResp(BaseResp resp) {
        // 发送到微信请求的响应结果
        if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) {
            // 登录授权回调
            SendAuth.Resp authResp = (SendAuth.Resp) resp;
            switch (resp.errCode) {
                case BaseResp.ErrCode.ERR_OK:
                    // 用户同意，获取code
                    String code = authResp.code;
                    RxBus.getInstance().post(new WxLoginEvent(code));
                    // 用code获取access_token
                    getAccessToken(code);
                    break;
                case BaseResp.ErrCode.ERR_AUTH_DENIED:
                    // 用户拒绝授权
                    ToastUtils.showLongToast(MyApplication.getContext(),"拒绝");
                    break;
                case BaseResp.ErrCode.ERR_USER_CANCEL:
                    ToastUtils.showLongToast(MyApplication.getContext(),"拒绝");
                    // 用户取消
                    break;
                default:
                    break;
            }
        }
        finish();
    }

    private void getAccessToken(String code) {
        // 实现获取access_token的逻辑
    }
}
